<template>
    <!-- 头部 -->
    <van-nav-bar :title="id ? '修改地址' : '新增地址'" l left-arrow @click-left="$router.back()">
        <template #right>
            <van-icon name="ellipsis" />
        </template>
    </van-nav-bar>
    <van-address-edit :address-info="info" :area-list="areaList" :show-delete="id ? true : false" show-set-default
        show-search-result :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @delete="onDelete" />
</template>
<script setup>
import { ref } from "vue"
import { areaList } from "@vant/area-data"
import { showToast } from 'vant'
import { addressAdd, getAddressId, editAddress, removeAddress } from "@/api/index.js"
import { useRouter, useRoute } from "vue-router"
let router = useRouter()
let route = useRoute()
let id = route.query.addressId;
if (id) {
    getDetail()
}
let info = ref({})
let onDelete = (item) => {
    removeAddress(item.id).then(res => {
        if (res.resultCode === 200) {
            showToast('删除成功')
            setTimeout(() => {
                router.back()
            }, 500)
        }
    })
}
let getAreaCode = (area) => {
    area = area.replace(/区|县/, '')
    for (let k in areaList.county_list) {
        if (areaList.county_list[k].includes(area)) {
            return k
        }
    }
}
// 获取地址详情
async function getDetail() {
    let { data } = await getAddressId(id)
    info.value = {
        id: data.addressId,
        name: data.userName,
        tel: data.userPhone,
        province: data.provinceName,
        city: data.cityName,
        county: data.regionName,
        addressDetail: data.detailAddress,
        areaCode: getAreaCode(data.regionName),
        isDefault: data.defaultFlag ? true : false
    }

}
// 保存
let onSave = (obj) => {
    let option = {
        'cityName': obj.city,
        'defaultFlag': obj.isDefault ? 1 : 0,
        'detailAddress': obj.addressDetail,
        'provinceName': obj.province,
        'regionName': obj.county,
        'userName': obj.name,
        'userPhone': obj.tel,
        'areaCode': obj.areaCode,
        'postalCode': ''
    }
    if (id) {
        editAddress({ ...option, addressId: id }).then(res => {
            if (res.resultCode === 200) {
                showToast('修改成功')
                router.push('/addressList')
            }
        })
    } else {
        addressAdd({ ...option }).then((res) => {
            if (res.resultCode == 200) {
                showToast('新增成功')
                router.push('/addressList')
            }
        })
    }
}

</script>